package com.kai.service.rabbitmq.consumer;

import com.kai.service.article.entity.ArticleOperateRecord;
import com.kai.service.article.service.IArticleOperateRecordService;
import com.kai.service.data.request.article.ArticleOperatorRequest;
import com.kai.service.enums.ArticleOperateTypeEnum;
import com.kai.service.rabbitmq.constant.RabbitmqConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Objects;


/**
 * 消费者
 */
@Component
@Slf4j
public class RabbitmqConsumer implements RabbitmqConstant {

    @Autowired
    private IArticleOperateRecordService articleOperateRecordService;

    private final static String TRUE = "true";

    private final static String FALSE = "false";

    /**
     * 文章操作消息接收
     *
     * @param request
     */
    @RabbitListener(bindings = {@QueueBinding(value = @Queue(value = ARTICLE_OPERATOR_QUEUE_NAME, durable = TRUE), exchange = @Exchange(DIRECT_EXCHANGE_NAME), key = {ARTICLE_OPERATOR_ROUTING_KEY})})
    public void articleOperateReceive(@Payload ArticleOperatorRequest request) {
        Long userId = request.getUserId();
        Long articleId = request.getArticleId();
        ArticleOperateTypeEnum operateType = request.getOperateType();

        ArticleOperateRecord articleOperateRecord = articleOperateRecordService.lambdaQuery()
                .eq(ArticleOperateRecord::getArticleId, articleId)
                .eq(ArticleOperateRecord::getUserId, userId)
                .eq(ArticleOperateRecord::getOperateType, operateType.name())
                .one();

        switch (operateType) {
            case READ:
                if (Objects.nonNull(articleOperateRecord)) {
                    articleOperateRecord.setCreateDatetime(request.getCreateDatetime());
                    articleOperateRecordService.updateById(articleOperateRecord);
                    return;
                }
                break;
            case LIKE:
            case NOLIKE:
            case COLLECT:
                if (Objects.nonNull(articleOperateRecord)) {
                    articleOperateRecordService.removeById(articleOperateRecord.getId());
                    return;
                }
                break;
        }

        articleOperateRecord = new ArticleOperateRecord()
                .setArticleId(request.getArticleId())
                .setOperateType(request.getOperateType().name())
                .setUserId(request.getUserId())
                .setCreateDatetime(request.getCreateDatetime());
        articleOperateRecordService.save(articleOperateRecord);
    }

}
